#include "pseudo_pkt.h"

#include <sqlite3.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>


#include <netinet/in.h>

#include "queue.h"

#ifdef DEBUG_MEM
extern long mem_free;
extern long mem_alloc;
#endif

#include "logger.h"

#define MAX_SIZE 256

void logger(void* q)
{
  printf("Starting Logger ...\n");
  Queue_t *Q;
  Q = (Queue_t*)q;
  pseudo_pkt* pkt;

  // open sqlite3 DB
  sqlite3 *conn;
  //sqlite3_stat *res;
  int error = 0;
  int rec_count = 0;
  const char* errMSG;
  const char* tail;


  error = sqlite3_open("loggerDB.sqlite3", &conn);
  if (error) {
	fprintf(stderr, "cannot open database");
	exit;
  }

  
  struct tm today;
  struct timeval *tt;

  int rc;
  char sql_stmt[1024];
  char *zErrMsg = 0;
  sqlite3_stmt *plineInfo = 0;

  char *saddr;
  char *daddr;
  int count = 0;
  /* loop */
  while(1) {
	// pop queue
	pkt = (pseudo_pkt*)queue_dequeue(Q->logQ);

	printf("LOG: Count:%d\n", count++);
	today = *localtime((time_t*)&(pkt->timestamp).tv_sec);
	
	saddr = strdup((char*)inet_ntoa(pkt->saddr));
	daddr = strdup((char*)inet_ntoa(pkt->daddr));
	print_pkt(pkt, 1);
	// format string

	memset(sql_stmt, 0, sizeof(sql_stmt) );

	sprintf(sql_stmt, "insert into LOG_%d%02d%02d (timestamp, saddr, sport, daddr, dport, protocol, type1, type2, type3, what) values(%ld.%ld, \"%s\", %d, \"%s\", %d, %d, %d, %d, %d, ?);",
		   today.tm_year+1900, today.tm_mon+1, today.tm_mday,
			(pkt->timestamp).tv_sec, (pkt->timestamp).tv_usec,
			saddr, pkt->sport,
			daddr, pkt->dport,
			pkt->protocol,
			pkt->type1, pkt->type2, pkt->type3);

	rc = sqlite3_prepare_v2(conn, sql_stmt, -1, &plineInfo, NULL);
	//rc = sqlite3_prepare_v2(conn, sql_stmt, -1, &plineInfo, NULL);
	if ( rc ) {
	  printf("SQL:%s\n", sql_stmt);
	  fprintf(stderr,"Error:%s\n", sqlite3_errmsg(conn));
	  continue;
	}
	//sqlite3_bind_text(plineInfo, 1, saddr, 15, NULL);
	//sqlite3_bind_text(plineInfo, 2, daddr, 15, NULL);
	rc = sqlite3_bind_blob(plineInfo, 1, pkt->payload, MAX_SIZE, NULL);
	if (rc) {
	  fprintf(stderr,"Error:%s\n", sqlite3_errmsg(conn));
	  continue;
	}

	rc = sqlite3_step(plineInfo);
	//if ( rc > 0) fprintf(stderr, "Error:%s\n", sqlite3_errmsg(conn));
	//sqlite3_reset(sql_stmt);	
	//printf("%s\n", sql_stmt);
	// push into DB
	// free
	free(saddr);
	free(daddr);
	free(pkt);
  }

  pthread_exit(NULL);
}
